import { _decorator, Animation, BoxCollider2D, Camera, Component, Contact2DType, director, find, instantiate, Label, Node, path, Prefab, resources, sp, Sprite, SpriteFrame, Tween, tween, UITransform, v2, v3 } from 'cc';
import { Dictionary } from './Dictionary';
import { biontTypeEnum } from './Enum';
import { Biont } from './Biont';
import { Player } from './Player';
import { Prop } from './Prop';
import { getDistance, randowNum } from './utils';
import { AudioMgr } from './AudioMgr';
import { UserInfo } from './UserInfo';
import { Adsdk } from './Adsdk';
const { ccclass, property } = _decorator;

@ccclass('gameMgr')
export class gameMgr extends Component {

    biontRoot;
    plantRoot;
    propRoot;
    @property(Node)
    playerRoot:Node;
    @property(Node)
    otherBiontRoot;
    @property(Prefab)
    plantPre:Prefab;
    @property(Prefab)
    propPre:Prefab;
    @property([SpriteFrame])
    plantSps:SpriteFrame[]=[]
    @property(Node)
    musicBtn:Node;

    static ins:gameMgr=null
    mapBoundary=v2(5500,5500)

    totalBiontTypeNum=12;
    currExistBiontsTotalNum=0;//当前场上存在生物总数
    existBiontsTotalNum=160;//场上存在生物总数
    isGameOver=false;

    // additionBiontPrefabArr=[]

    biontId=0;
    existBiontsDic:Dictionary<number,Node>=new Dictionary();//存在生物的数组

    protected onLoad(): void {
    gameMgr.ins=this;
        this.biontRoot=find("Canvas/biontRoot")
        this.plantRoot=find("Canvas/plantRoot")
        this.propRoot=find("Canvas/propRoot")
    }

    start() {
        // for (let i = 0; i < 12; i++) {
        //     resources.load(`prefabe/additionPre/${i}`, Prefab, (err, res) => {
        //         gameMgr.ins.additionBiontPrefabArr.push(res);
        //     })
        // }

            // this.generateBiont(biontTypeEnum.kedou, 40)
            // this.generateBiont(biontTypeEnum.qingwa, 15)
            // this.generateBiont(biontTypeEnum.wugui, 12)
            // this.generateBiont(biontTypeEnum.jinyu, 8)
            // this.generateBiont(biontTypeEnum.liyu, 5)
            // this.generateBiont(biontTypeEnum.changyu, 4)
            // this.generateBiont(biontTypeEnum.shayu, 3)
            // this.generateBiont(biontTypeEnum.jingyu, 2)
            // this.generateBiont(biontTypeEnum.changyu2, 1)

            this.generateBiont(biontTypeEnum.kedou0, 40)
            this.generateBiont(biontTypeEnum.kedou1, 40)
            this.generateBiont(biontTypeEnum.qingwa, 40)
            this.generateBiont(biontTypeEnum.wugui, 40)


            this.generateFixPlant(Player.ins.node.position.x+randowNum(-200,-100),Player.ins.node.position.y+randowNum(-200,200))
            this.generateFixPlant(Player.ins.node.position.x+randowNum(200,100),Player.ins.node.position.y+randowNum(-200,200))
            this.generatePlant(150);
            // this.generateProp(100);

            if (UserInfo.isHasAudio) {
                resources.load("IconImg/music-on/spriteFrame", SpriteFrame, (err, res) => {
                    this.musicBtn.getComponent(Sprite).spriteFrame =res;
               })
                AudioMgr.ins.play("audio/bgm", 1)
            }
            else{
                resources.load("IconImg/music-off/spriteFrame", SpriteFrame, (err, res) => {
                    this.musicBtn.getComponent(Sprite).spriteFrame =res;
               })
               AudioMgr.ins.stop();

            }

    }


    generateBiont(biontType,num) {
        resources.load(`prefabe/fiont/${biontType}`, Prefab, (err, res) => {
            for (let i = 0; i < num; i++) {
                let pre = instantiate(res);
                pre.setParent(this.biontRoot);
                if (biontType == biontTypeEnum.wugui || biontType == biontTypeEnum.changlong) {
                    pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "walk", true)
                }
                else {
                    pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "animation", true)
                }
                let result = false;
                while (result == false) {
                    let randPos = v3(randowNum(-gameMgr.ins.mapBoundary.x, gameMgr.ins.mapBoundary.x), randowNum(-gameMgr.ins.mapBoundary.y, gameMgr.ins.mapBoundary.y), 0);
                    let randPosWorld=this.node.getComponent(UITransform).convertToWorldSpaceAR(randPos);
        
                    let selfWorldPos = Player.ins.node.getWorldPosition();
        
                    if (getDistance(selfWorldPos.x,selfWorldPos.y,randPosWorld.x,randPosWorld.y)>2000) {
                        result = true;
                        pre.setPosition(randPos.x,randPos.y);
                    }
        
                }
                pre.getComponent(Biont).init(this.biontId,biontType,true,true);
                this.existBiontsDic.set(this.biontId,pre);
                this.biontId+=1;
                this.currExistBiontsTotalNum+=1;
            }
        })

        
    }

    //生成植物
    generatePlant(num) {
        for (let i = 0; i < num; i++) {
            let pre = instantiate(this.plantPre);
            pre.setParent(this.plantRoot);
            pre.setPosition(this.randowNum(-this.mapBoundary.x, this.mapBoundary.x), this.randowNum(-this.mapBoundary.y, this.mapBoundary.y))
            pre.getChildByName("sp").getComponent(Sprite).spriteFrame =this.plantSps[this.randowNum(0,3)];
            let randScale=randowNum(0.7,1.3)
            pre.setScale(randScale,randScale,1);
        }
    }

    //生成固定植物
    generateFixPlant(posX,posY) {
            let pre = instantiate(this.plantPre);
            pre.setParent(this.plantRoot);
            pre.setPosition(posX,posY);
            pre.getChildByName("sp").getComponent(Sprite).spriteFrame =this.plantSps[this.randowNum(0,3)];
    }

    test(){
        console.log(this.currExistBiontsTotalNum,"currExistBiontsTotalNum");
    }

     //生成道具
     generateProp(num) {
        for (let i = 0; i < num; i++) {
            let pre = instantiate(this.propPre);
            pre.setParent(this.propRoot);
            pre.setPosition(this.randowNum(-this.mapBoundary.x, this.mapBoundary.x), this.randowNum(-this.mapBoundary.y, this.mapBoundary.y))
            pre.getComponent(Prop).init(this.randowNum(0,1))
        }
    }

    protected update(dt: number): void {
        if (this.currExistBiontsTotalNum<this.existBiontsTotalNum) {//生物数量保持一致
            // let randClass=this.randowNum(0,10);
            // let randNumBiontType;
            // if (randClass < 5) {//4成几率
            //     randNumBiontType = this.randowNum(0, 2);
            // }
            // else if (5<=randClass&&randClass<= 8) {//4成几率
            //     randNumBiontType = this.randowNum(3, 5);
            // }
            // else{//2成几率
            //     randNumBiontType = this.randowNum(6, 7);
            // }
            // console.log("生物保持一致","生成",randNumBiontType)
            // this.generateBiont(randNumBiontType,1)
            let minNum;
            let maxNum;
            console.log(Player.ins.currControlBiontType,"Player.ins.currControlBiontType")
            if (Player.ins.currControlBiontType - 2 < 0) {
                minNum = 0
            }
            else {
                minNum = Player.ins.currControlBiontType - 2;
            }

            if (Player.ins.currControlBiontType +3 > this.totalBiontTypeNum-2) {
                maxNum = this.totalBiontTypeNum-2
            }
            else {
                maxNum = Player.ins.currControlBiontType +3;
            }

            let randNumBiontType = this.randowNum(minNum,maxNum);

            console.log("生物保持一致", "生成", randNumBiontType)
            this.generateBiont(randNumBiontType, 1);
        }
    }


    randowNum(min: number, max: number) {

        let ret = Math.floor(Math.random() * (max - min + 1)) + min;

        return ret;
    }

    failPanelOnclickReStart(){
        // AudioMgr.ins.playOneShot("audio/btn",0.7)

        // gameMgr.ins.isGameOver=false;
        // console.log("重新开始")

        // let failPanelNode = find("Canvas/failPanel")
        // this.closeFailPanel()
        
        // this.playerRoot.removeAllChildren()

        // resources.load("prefabe/fiont/0", Prefab, (err, res) => {
        //     let pre = instantiate(res);
        //     pre.setParent(this.playerRoot);
        //     pre.setPosition(0, 0, 0)
        //     pre.getComponent(Biont).init(-1,biontTypeEnum.kedou0, false)
        //     pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "animation", true)
        //     pre.angle = 0;
        //     pre.getChildByName("shield2").active=true;
        //     pre.getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT, Player.ins.beginContact)

        // })

        // find("Canvas/Camera").getComponent(Camera).orthoHeight=1000;
        // this.otherBiontRoot.removeAllChildren();
        // Player.ins.currControlBiontType=biontTypeEnum.kedou1;
        // Player.ins.hasBiontsDic.clear();
        // Player.ins.hasBiontsDic.set(999,Player.ins.currControlBiontType);
        // Player.ins.IsImmortal=true;
        // Player.ins.changeOtherBiontType();

        UserInfo.isWudiMode = false;
        AudioMgr.ins.playOneShot("audio/btn",0.7)
        director.loadScene("main")
    }

    failPanelOnclickRevive() {
        Adsdk.instance.showVideo(()=>{
            AudioMgr.ins.playOneShot("audio/btn",0.7)
            gameMgr.ins.isGameOver=false;
            if(this.playerRoot.children[0]){
                this.playerRoot.children[0].getChildByName("dieEffect").active=false;
            }
            this.closeFailPanel()
            Player.ins.IsImmortal=true;

        },()=>{
            console.log('复活失败')
        })
    }

    openFailPanel() {
        AudioMgr.ins.playOneShot("audio/fail",0.7)
        let failPanelNode = find("Canvas/failPanel")
        failPanelNode.active = true;
        Adsdk.instance.showInterstitialAd()
        Adsdk.instance.hideGridAdTop()
        Adsdk.instance.showGridAdTop()
        failPanelNode.getChildByName("biontNode").removeAllChildren();
        tween(failPanelNode.getChildByName("light"))
            .by(1, { angle: 360 })
            .union()
            .repeatForever()
            .start()

        resources.load(`prefabe/failDisplayBiontPre/${Player.ins.currControlBiontType}`, Prefab, (err, res) => {
            console.log("Player.ins.currControlBiontType",Player.ins.currControlBiontType)
            console.log(res,"res")
            let pre = instantiate(res);
            pre.setParent(failPanelNode.getChildByName("biontNode"));
            pre.angle=180
            // if (Player.ins.currControlBiontType == biontTypeEnum.wugui || Player.ins.currControlBiontType == biontTypeEnum.changlong) {
            //     pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "walk", true)
            // }
            // else {
            //     pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "animation", true)
            // }
        })
    }
    closeFailPanel() {
        let failPanelNode = find("Canvas/failPanel")
        failPanelNode.active = false;
        Adsdk.instance.hideGridAdTop()
        Tween.stopAllByTarget(failPanelNode.getChildByName("light"))
    }

    gameEnd() {
        let endPanel = find("Canvas/endPanel");
        endPanel.active = true
        Adsdk.instance.showInterstitialAd()
        // endPanel.getComponent(Animation).play("long")
        setTimeout(() => {
            AudioMgr.ins.playOneShot("audio/lightning", 0.7)
        }, 1000)
        this.scheduleOnce(() => {
            endPanel.getChildByName("notIndependentBiontPre").active = true;
            endPanel.getChildByName("comfirmBtn").active = true
            AudioMgr.ins.playOneShot("audio/succ", 0.5)

        }, 5)
    }

    onclickEndPanelComfirmBtn(){
        AudioMgr.ins.playOneShot("audio/btn",0.7)

        director.loadScene("start")
    }

    onclickReturnHomeBtn() {
        director.loadScene("start");
    }

    onclickAudioBtn() {
        if (UserInfo.isHasAudio) {
            UserInfo.isHasAudio = false;
            AudioMgr.ins.stop();

            resources.load("IconImg/music-off/spriteFrame", SpriteFrame, (err, res) => {
                this.musicBtn.getComponent(Sprite).spriteFrame =res;
           })

            // this.audioLabel.string="声音开"
        }
        else {
            UserInfo.isHasAudio = true;
            AudioMgr.ins.play("audio/bgm", 1)

            // this.audioLabel.string="声音关"

            resources.load("IconImg/music-on/spriteFrame", SpriteFrame, (err, res) => {
                this.musicBtn.getComponent(Sprite).spriteFrame =res;
           })

        }
    }



}


